<!--
 * @author  dumeng
 新建视频
-->
<template>
  <div class="courseware-create">
    <el-dialog
      v-el-drag-dialog
      :visible.sync="visible"
      :title="info.subjectName ? '重新转码' : '新建视频'"
      center
      :close-on-click-modal="false"
      width="600px"
      :show-close="false"
      custom-class="courseware-create-dialog"
      @close="$emit('close')"
    >
      <section v-loading="loading" class="courseware-create-main">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="form">
          <template v-if="uploadFile.oldfile && uploadFile.oldfile.name">
            <el-form-item label="转码失败原因" prop="subjectType">
              <el-input
                v-model="info.transcodeFailReason"
                type="textarea"
                disabled
                :autosize="{ minRows: 3, maxRows: 6 }"
                placeholder="请输入内容"
              />
            </el-form-item>
          </template>
          <template v-if="uploadFile.oldfile && uploadFile.oldfile.name">
            <el-form-item label="原视频">
              <div class="select-data">
                {{ uploadFile.oldfile.name }}
              </div>
              <el-button size="mini" type="text" @click="preview.state = true">查看</el-button>
              <el-button size="mini" type="text" @click="downLoad">下载</el-button>
            </el-form-item>
          </template>
          <el-form-item label="视频类型" prop="subjectType">
            <el-radio-group v-model="form.subjectType">
              <el-radio label="KCLX01">本系统</el-radio>
              <el-radio label="KCLX04">课通云</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="视频名称" prop="subjectName">
            <el-input v-model.trim="form.subjectName" maxlength="100" placeholder="" />
          </el-form-item>
          <el-form-item label="视频分类" prop="subjectClassify">
            <el-cascader
              ref="classify"
              v-model="form.subjectClassify"
              style="width:100%"
              clearable
              :props="createClassifyProps"
              :options="classifyOptions"
            />
          </el-form-item>
          <template v-if="form.subjectType === 'KCLX01'">
            <el-form-item :label="info.id ? '重新上传视频' : '视频上传'" prop="courseId">
              <div v-if="!uploadFile.file" class="selectbtn" @click="uploadFile.showUpload = true">开始上传</div>
              <template v-else>
                <div :key="form.courseId" class="select-data">
                  {{ uploadFile.file.name }}
                  <i class="el-icon-close" @click="clearFile" />
                </div>
              </template>
              <Upload
                v-if="uploadFile.showUpload"
                ref="upload"
                :accept="uploadFile.accept"
                :limit="1"
                :show-chunks="true"
                :multiple="false"
                :chunk-size="uploadFile.chunksize"
                @close="uploadFile.showUpload = false"
                @success="uploadSuccess"
              >
                <div slot="tip" class="upload-tip">
                  <i class="el-icon-info" />
                  : 只能上传：{{ form.subjectType | filterTip }}
                </div>
              </Upload>
              <p v-if="info.id" style="color: red;margin:0;"><i class="el-icon-info" />如果不重新上传视频，表示再次对原视频进行转码</p>
            </el-form-item>

            <el-form-item label="是否上传水印" prop="isHaveWatermark">
              <el-radio-group v-model="form.isHaveWatermark" @change="changeFileAccept">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.isHaveWatermark === '1'" label="选择水印模板" prop="watermarkId">
              <el-select v-model="form.watermarkId" placeholder="请选择" style="width:100%" @change="handleWatermarkId">
                <el-option v-for="item in watermarkOptions" :key="item.id" :label="item.watermarkName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.isHaveWatermark === '1' && form.watermarkId !== ''">
              <el-image style="width:100%;height: auto" :src="form.watermarkIconUrl" />
            </el-form-item>
          </template>
          <template v-if="form.subjectType === 'KCLX04'">
            <el-form-item label="课程id" prop="ktyCourseId">
              <el-input v-model.trim="form.ktyCourseId" maxlength="100" placeholder="" />
            </el-form-item>
            <el-form-item label="课程章节资源id" prop="ktyCourseItemId">
              <el-input v-model.trim="form.ktyCourseItemId" maxlength="100" placeholder="" />
            </el-form-item>
          </template>
        </el-form>
      </section>
      <section slot="footer" class="dialog-footer">
        <el-button style="padding: 10px 30px;" @click="$emit('close',0)">取 消</el-button>
        <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
      </section>
    </el-dialog>
    <el-dialog
      v-if="preview.state"
      v-el-drag-dialog
      :fullscreen="isFull"
      custom-class="courseware-preview"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="preview.state"
      title="预览"
      center
      width="600px"
      @close="preview.state = false"
    >
      <div class="full">
        <el-button size="small" type="primary" icon="el-icon-full-screen" @click="isFull = !isFull">
          {{ isFull ? '取消全屏' : '全屏' }}
        </el-button>
      </div>
      <coursewareware-preview
        v-if="preview.state"
        :is-full="isFull"
        show-type="before"
        :type="preview.fileType"
        :file-id="preview.fileId"
      />
    </el-dialog>
  </div>
</template>

<script>
import Upload from './upload/index'
import { getClassifyTree, getDictByCode, insert, update, getwatermarkOptions } from '../api/createCourseware'
import { specialText } from '@/utils/validate'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import coursewarewarePreview from './CoursewarePreview'

export default {
  name: 'Create',
  components: { Upload, coursewarewarePreview },
  directives: { elDragDialog },
  filters: {
    filterTip(subjectType) {
      if (subjectType === 'KCLX01') {
        return '视频文件'
      } else if (subjectType === 'KCLX03') {
        return '音频文件'
      } else {
        return 'PDF文件'
      }
    }
  },
  props: {
    info: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      loading: false,
      form: {
        id: '',
        subjectName: '',
        subjectClassify: '',
        subjectType: 'KCLX01',
        courseId: '',
        subjectDuration: '',
        isHaveWatermark: '0',
        watermarkId: '',
        ktyCourseItemId: '',
        ktyCourseId: ''
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入视频名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 100 个字', trigger: 'blur' }
        ],
        subjectClassify: [{ required: true, message: '请选择视频分类', trigger: 'change' }],
        subjectType: [{ required: true, message: '请选择视频类型', trigger: 'change' }],
        ktyCourseItemId: [{ required: true, message: '请输入课通云课程章节资源id', trigger: 'blur' }],
        ktyCourseId: [{ required: true, message: '请输入课通云课程id', trigger: 'blur' }],
        courseId: [{ required: true, message: '请上传视频', trigger: 'change' }]
      },
      watermarkOptions: [],
      defaultWaterMark: {}, // 默认水印
      inputDuration: true, // 是否禁用输入视频时长
      createClassifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true
      },
      classifyOptions: [],
      uploadFile: {
        showUpload: false,
        accept: 'video/*',
        chunksize: 10 * 1024 * 1024,
        file: '',
        oldfile: ''
      },
      preview: {
        state: false,
        fileId: '',
        fileType: 1
      },
      view: '/API-DOCUMENT/document/file/download?id=',
      isFull: false, // 预览是否全屏
      visible: true
    }
  },
  watch: {
    'form.classifyIds': {
      handler(newName, oldName) {
        if (this.$refs.classify) {
          this.$refs.classify.dropDownVisible = false
        }
      },
      immediate: true,
      deep: true
    }
  },
  async created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    await this.getwatermarkOptions()
    this.getClassifyOption()
      .then(() => {
        for (const i in this.form) {
          if (i === 'subjectType') {
            this.form.subjectType = this.info[i] ? this.info[i] : 'KCLX01'
          } else if (i === 'isHaveWatermark') {
            this.form[i] = this.info[i] ? this.info[i] : '0'
          } else {
            this.form[i] = this.info[i] ? this.info[i] : ''
          }
        }
        this.changeFileAccept()
        this.$nextTick(() => {
          this.$refs['form'].clearValidate()
        })
        if (this.info.subjectName) {
          this.uploadFile.oldfile = { name: this.info.subjectName }
        }
        this.preview.fileId = this.info.courseId || ''
        this.preview.fileType = this.info.subjectType || ''
        console.log(this.info)
        this.loading = false
      })
      .catch((err) => {
        console.log('errList', err)
      })
  },
  methods: {
    downLoad() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '/API-DOCUMENT/document/file/download?id=' + this.info.courseId
      link.setAttribute('download', this.uploadFile.oldfile.name)
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    clearFile() {
      this.uploadFile.file = ''
      if (!this.info.id) {
        this.form.courseId = ''
      }
      this.form.subjectDuration = ''
    },
    /**
     * 格式化视频时长单位
     */
    fomatterTimeAndPage(t) {
      if (this.form.subjectType === 'KCLX02') {
        return '页'
      } else {
        const fTime = t || 0
        let time = parseInt(fTime) + '秒'
        if (parseInt(fTime) > 60) {
          var second = parseInt(fTime) % 60
          var min = parseInt(fTime / 60)
          time = min + '分' + second + '秒'

          if (min > 60) {
            min = parseInt(fTime / 60) % 60
            var hour = parseInt(parseInt(fTime / 60) / 60)
            time = hour + '小时' + min + '分' + second + '秒'

            if (hour > 24) {
              hour = parseInt(parseInt(fTime / 60) / 60) % 24
              var day = parseInt(parseInt(parseInt(fTime / 60) / 60) / 24)
              time = day + '天' + hour + '小时' + min + '分' + second + '秒'
            }
          }
        }
        return time
      }
    },
    /**
     * 获取水印分类
     */
    getwatermarkOptions() {
      this.loading = true
      return new Promise((resolve, reject) => {
        getwatermarkOptions({ status: 'ZT01' })
          .then(({ data }) => {
            this.loading = false
            this.watermarkOptions = data.data || []
            if (this.watermarkOptions.length > 0) {
              const obj = this.watermarkOptions.find((item) => item.isDefault === 1)
              this.defaultWaterMark = obj || {}
            } else {
              this.defaultWaterMark = {}
            }
            resolve()
          })
          .catch((error) => {
            this.loading = false
            reject(error)
          })
      })
    },
    /**
     * 获取视频分类
     */
    getClassifyOption() {
      this.loading = true
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'JNZQFL05' })
          .then(({ data }) => {
            this.classifyOptions = data.data || []
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /**
     * 切换是否上传水印
     */
    changeFileAccept() {
      this.$set(this.form, 'watermarkId', '')
      if (this.form.isHaveWatermark === '1' && Object.keys(this.defaultWaterMark).length > 0) {
        this.$set(this.form, 'watermarkIconUrl', this.defaultWaterMark.watermarkIconUrl)
        this.form.watermarkId = this.defaultWaterMark.id
      }
    },
    handleWatermarkId(el) {
      const isData = this.watermarkOptions.find((item) => item.id === el)
      this.$set(this.form, 'watermarkIconUrl', isData.watermarkIconUrl)
    },
    onSubmint() {
      if (this.info.id) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params.transcodeStatus = params.subjectType === 'KCLX02' ? '3' : '2'
            if (params.subjectClassify instanceof Array) {
              params['subjectClassify'] = params.subjectClassify.length > 0 ? params.subjectClassify[params.subjectClassify.length - 1] : ''
            }
            return new Promise((resolve, reject) => {
              update(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$emit('close')
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error update!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['subjectClassify'] = this.form.subjectClassify.length > 0 ? this.form.subjectClassify[this.form.subjectClassify.length - 1] : ''
            return new Promise((resolve, reject) => {
              insert(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$emit('close')
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    uploadSuccess(id, files) {
      if (id) {
        this.form.courseId = id
        this.form.subjectName = files[0].name.substring(0, files[0].name.lastIndexOf('.'))
        this.uploadFile.file = files[0]
        if (this.form.subjectType === 'KCLX02' && files[0].totalPages && files[0].totalPages > 0) {
          this.form.subjectDuration = files[0].totalPages
          this.uploadFile.showUpload = false
        } else if (this.form.subjectType !== 'KCLX02' && files[0].duration && files[0].duration > 0) {
          this.form.subjectDuration = files[0].duration
          this.uploadFile.showUpload = false
        } else {
          this.inputDuration = false
          this.$alert('视频格式不支持，请重新上传。', '提示', {
            confirmButtonText: '确定',
            callback: (action) => {
              this.clearFile()
            }
          })
        }
      }
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.courseware-create {
  .courseware-create-dialog .el-dialog__body {
    height: 80vh;
    overflow-y: auto;
  }

  .select-data {
    display: inline-block;
    background: rgba(246, 246, 246, 1);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(51, 51, 51, 1);
    padding: 0 10px;
    margin-right: 5px;
    margin-bottom: 8px;

    i {
      cursor: pointer;
      padding-left: 5px;
    }
  }

  .selectbtn {
    display: inline-block;
    width: 120px;
    background: rgba(255, 255, 255, 1);
    @include border-color(1px, dotted, $mainColor);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    @include font-color($mainColor);
    text-align: center;
    cursor: pointer;
  }

  /*  .courseware-create-footer {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      text-align: center;
      padding: 10px 0;
      background-color: white;
      box-shadow: 0 -3px 6px #f5f5f5;
    }*/

  .courseware-preview {
    .el-dialog__body {
      position: relative;

      .full {
        position: absolute;
        width: 100px;
        height: 58px;
        right: 50px;
        top: -58px;
        display: flex;
        align-items: center;
        text-align: right;
      }
    }
  }
}
</style>
